/*
 * @Author: zhangchaosen
 * @Date: 2024-05-20 09:29:53
 * @LastEditors: zhangchaosen
 * @LastEditTime: 2024-05-20 10:04:00
 * @Description:
 */
/** 统一处理 Cookie */
import type { LoginRequestData } from '@/api/login/type'
import CacheKey from '@/constants/cache-key'
import Cookies from 'js-cookie'

/**
 ** 字符串加密
 * @param code 需要加密的文本
 */
function encodeStr(code: string): string {
  let c: string = String.fromCharCode(code.charCodeAt(0) + code.length)
  for (let i = 1; i < code.length; i++) {
    c += String.fromCharCode(code.charCodeAt(i) + code.charCodeAt(i - 1))
  }
  return btoa(encodeURIComponent(c))
}

/**
 ** 字符串解密
 * @param code 需要解密的文本
 */
function decodeStr(code: string): string {
  try {
    const codes = decodeURIComponent(atob(code))
    let c: string = String.fromCharCode(codes.charCodeAt(0) - codes.length)
    for (let i = 1; i < codes.length; i++) {
      c += String.fromCharCode(codes.charCodeAt(i) - c.charCodeAt(i - 1))
    }
    return c
  } catch {
    return ''
  }
}

/**
 * 从cookie中获取token
 * @returns 解密后的token
 */
export const getToken = (): string => {
  const token: string | undefined = Cookies.get(CacheKey.TOKEN_KEY)
  return token || ''
}

/**
 * 设置token
 * @param token token值
 */
export const setToken = (token: string): void => {
  Cookies.set(CacheKey.TOKEN_KEY, token, { expires: CacheKey.TOKEN_EXPIRES })
}

/**
 * 删除token
 */
export const removeToken = (): void => {
  Cookies.remove(CacheKey.TOKEN_KEY)
}

/**
 * 获取cookie中存储的账号密码
 * @returns 存储的账号密码
 */
export const getRemember = (): LoginRequestData | undefined => {
  const data: string | undefined = Cookies.get(CacheKey.REMEMBER_KEY)
  if (data) {
    try {
      const loginData = JSON.parse(decodeStr(data))
      return loginData && typeof loginData === 'object' ? loginData : undefined
    } catch {
      return undefined
    }
  }
  return undefined
}

/**
 * 存储账号密码
 * @param loginInfo 账号密码对象
 */
export const setRemember = (loginInfo: LoginRequestData): void => {
  if (loginInfo && typeof loginInfo === 'object') {
    Cookies.set(CacheKey.REMEMBER_KEY, encodeStr(JSON.stringify(loginInfo)), { expires: CacheKey.REMEMBER_DAY })
  }
}

/**
 * 清除账号密码
 */
export const removeRemember = (): void => {
  Cookies.remove(CacheKey.REMEMBER_KEY)
}
